<template>
  <div class="role-square-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">角色广场</h1>
        <p class="page-subtitle">发现更多有趣的AI角色</p>
        
        <!-- 热门角色区域 -->
        <div v-if="hotRoles.length > 0" class="hot-roles-section">
          <h2 class="section-title">🔥 热门角色</h2>
          <div class="hot-roles-grid">
            <div v-for="role in hotRoles" :key="role.id" class="hot-role-card" @click="viewRoleDetails(role)">
              <div class="hot-role-avatar">
                <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
                <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
              </div>
              <div class="hot-role-info">
                <h3 class="hot-role-name">{{ role.name }}</h3>
                <p class="hot-role-desc">{{ role.description || '暂无描述' }}</p>
                <div class="hot-role-stats">
                  <span class="stat">💬 {{ role.usageCount || 0 }}</span>
                  <span class="stat">⭐ {{ role.averageRating || 0 }}</span>
                  <span class="stat">❤️ {{ role.favoriteCount || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 角色分类区域 -->
        <div class="categories-section">
          <h2 class="section-title">📂 角色分类</h2>
          <div class="categories-grid">
            <div v-for="category in categories" :key="category.key" 
                 :class="['category-card', { active: activeCategory === category.key }]"
                 @click="setActiveCategory(category.key)">
              <div class="category-icon">{{ category.icon }}</div>
              <div class="category-info">
                <h3 class="category-name">{{ category.name }}</h3>
                <p class="category-desc">{{ category.description }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <div class="search-bar">
          <input 
            v-model="searchKeyword" 
            type="text" 
            placeholder="搜索角色名称、描述或标签..."
            class="search-input"
            @input="onSearchInput"
          />
          <button class="search-btn" @click="searchRoles">🔍</button>
        </div>
        
        <div class="filter-tabs">
          <button 
            v-for="tab in filterTabs" 
            :key="tab.key"
            :class="['filter-tab', { active: activeFilter === tab.key }]"
            @click="setActiveFilter(tab.key)"
          >
            {{ tab.label }}
          </button>
        </div>
      </div>
      
      <div v-if="loading" class="loading-grid">
        <div v-for="i in 8" :key="i" class="role-card skeleton">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-title"></div>
            <div class="skeleton-desc"></div>
          </div>
        </div>
      </div>
      
      <div v-else-if="roles.length === 0" class="empty-state">
        <div class="empty-icon">🎭</div>
        <h3>暂无角色</h3>
        <p>{{ searchKeyword ? '没有找到匹配的角色' : '还没有角色发布到广场' }}</p>
      </div>
      
      <div v-else class="roles-grid">
        <div v-for="role in roles" :key="role.id" class="role-card" @click="viewRoleDetails(role)">
          <div class="role-avatar">
            <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
            <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
          </div>
          
          <div class="role-info">
            <h3 class="role-name">{{ role.name }}</h3>
            <p class="role-desc">{{ role.description || '暂无描述' }}</p>
            
            <div class="role-stats">
              <div class="stat">
                <span class="stat-icon">💬</span>
                <span class="stat-value">{{ role.usageCount || 0 }}</span>
                <span class="stat-label">使用</span>
              </div>
              <div class="stat">
                <span class="stat-icon">⭐</span>
                <span class="stat-value">{{ role.averageRating || 0 }}</span>
                <span class="stat-label">评分</span>
              </div>
              <div class="stat">
                <span class="stat-icon">❤️</span>
                <span class="stat-value">{{ role.favoriteCount || 0 }}</span>
                <span class="stat-label">收藏</span>
              </div>
            </div>
            
            <div v-if="role.tags" class="role-tags">
              <span v-for="tag in role.tags.split(',')" :key="tag" class="tag">
                {{ tag.trim() }}
              </span>
            </div>
          </div>
          
          <div class="role-actions">
            <button class="action-btn primary" @click.stop="startChat(role)">开始对话</button>
            <button class="action-btn" @click.stop="toggleFavorite(role)">
              {{ role.isFavorited ? '❤️' : '🤍' }}
            </button>
          </div>
        </div>
      </div>
      
      <div class="load-more" v-if="hasMore && !loading">
        <button class="load-more-btn" @click="loadMoreRoles">加载更多</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const roles = ref([])
const hotRoles = ref([])
const searchKeyword = ref('')
const activeFilter = ref('latest')
const activeCategory = ref('all')
const pageNo = ref(1)
const pageSize = 12
const hasMore = ref(true)
let searchTimeout = null

const categories = [
  { key: 'all', name: '全部', description: '所有角色', icon: '🌟' },
  { key: 'assistant', name: '助手', description: '智能助手类角色', icon: '🤖' },
  { key: 'entertainment', name: '娱乐', description: '娱乐聊天类角色', icon: '🎭' },
  { key: 'education', name: '教育', description: '学习教育类角色', icon: '📚' },
  { key: 'business', name: '商务', description: '商务办公类角色', icon: '💼' },
  { key: 'creative', name: '创作', description: '创意设计类角色', icon: '🎨' },
  { key: 'life', name: '生活', description: '生活服务类角色', icon: '🏠' }
]

const filterTabs = [
  { key: 'latest', label: '最新' },
  { key: 'popular', label: '最受欢迎' },
  { key: 'rating', label: '评分最高' },
  { key: 'favorite', label: '收藏最多' }
]

const loadHotRoles = async () => {
  try {
    const res = await fetch('/api/roles/hot')
    const data = await res.json()
    
    if (data.code === 0) {
      hotRoles.value = data.data || []
    } else {
      console.error('获取热门角色失败:', data.message)
    }
  } catch (e) {
    console.error('获取热门角色失败', e)
  }
}

const loadRoles = async (reset = false) => {
  if (loading.value) return
  
  if (reset) {
    pageNo.value = 1
    hasMore.value = true
    roles.value = []
  }
  
  if (!hasMore.value) return
  
  loading.value = true
  
  try {
    const params = new URLSearchParams({
      pageNo: String(pageNo.value),
      pageSize: String(pageSize),
      status: 'PUBLISHED',
      privacy: 'PUBLIC',
      sortBy: getSortBy(),
      asc: 'false'
    })
    
    if (searchKeyword.value.trim()) {
      params.set('keyword', searchKeyword.value.trim())
    }
    
    // 添加分类筛选
    if (activeCategory.value !== 'all') {
      params.set('category', activeCategory.value)
    }
    
    const res = await fetch(`/api/roles/search?${params.toString()}`)
    const data = await res.json()
    
    if (data.code === 0) {
      const records = data.data?.records || []
      if (records.length < pageSize) {
        hasMore.value = false
      }
      
      if (reset) {
        roles.value = records
      } else {
        roles.value = roles.value.concat(records)
      }
      
      pageNo.value += 1
    } else {
      console.error('获取角色列表失败:', data.message)
    }
  } catch (e) {
    console.error('获取角色列表失败', e)
  } finally {
    loading.value = false
  }
}

const getSortBy = () => {
  switch (activeFilter.value) {
    case 'popular': return 'usageCount'
    case 'rating': return 'averageRating'
    case 'favorite': return 'favoriteCount'
    default: return 'createdAt'
  }
}

const setActiveCategory = (category) => {
  activeCategory.value = category
  loadRoles(true)
}

const setActiveFilter = (filter) => {
  activeFilter.value = filter
  loadRoles(true)
}

const onSearchInput = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    loadRoles(true)
  }, 500)
}

const searchRoles = () => {
  loadRoles(true)
}

const loadMoreRoles = () => {
  loadRoles(false)
}

const viewRoleDetails = (role) => {
  router.push(`/public-role/${role.id}`)
}

const startChat = (role) => {
  router.push(`/chat/${role.id}`)
}

const toggleFavorite = async (role) => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    const res = await fetch(`/api/roles/${role.id}/favorite`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    const data = await res.json()
    if (data.code === 0) {
      role.isFavorited = !role.isFavorited
      role.favoriteCount = (role.favoriteCount || 0) + (role.isFavorited ? 1 : -1)
    } else {
      console.error('收藏操作失败:', data.message)
    }
  } catch (e) {
    console.error('收藏操作失败', e)
  }
}

onMounted(() => {
  loadHotRoles()
  loadRoles(true)
})
</script>

<style scoped>
.role-square-page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

/* 热门角色样式 */
.hot-roles-section {
  margin-bottom: 40px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 16px;
  color: white;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

.hot-roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
}

.hot-role-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.hot-role-card:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.hot-role-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 12px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.hot-role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hot-role-name {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 6px;
  color: white;
}

.hot-role-desc {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 12px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hot-role-stats {
  display: flex;
  gap: 12px;
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.9);
}

.hot-role-stats .stat {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 角色分类样式 */
.categories-section {
  margin-bottom: 40px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.category-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid #e5e7eb;
  text-align: center;
}

.category-card:hover {
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(102, 126, 234, 0.1);
}

.category-card.active {
  border-color: #667eea;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.category-icon {
  font-size: 2rem;
  margin-bottom: 12px;
}

.category-name {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 6px;
  color: inherit;
}

.category-desc {
  font-size: 0.9rem;
  color: inherit;
  opacity: 0.8;
}

.page-subtitle {
  font-size: 1.125rem;
  color: #6b7280;
  margin-bottom: 32px;
}

.search-bar {
  display: flex;
  max-width: 500px;
  margin: 0 auto 24px;
  gap: 8px;
}

.search-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.2s;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
}

.search-btn {
  padding: 12px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.2s;
}

.search-btn:hover {
  background: #5a67d8;
}

.filter-tabs {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.filter-tab {
  padding: 8px 16px;
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 20px;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.filter-tab.active {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

.filter-tab:hover:not(.active) {
  border-color: #d1d5db;
  background: #f9fafb;
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.role-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
  transition: all 0.3s;
  cursor: pointer;
}

.role-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.1);
  border-color: #667eea;
}

.role-avatar {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 32px;
  font-weight: 600;
}

.role-status {
  position: absolute;
  top: -4px;
  right: -4px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.status-badge.published {
  background: #10b981;
}

.role-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.role-desc {
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.role-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
}

.stat-icon {
  font-size: 16px;
}

.stat-value {
  font-weight: 500;
}

.stat-label {
  font-size: 12px;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 16px;
}

.tag {
  background: #e0e7ff;
  color: #3730a3;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.action-btn.primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.action-btn:not(.primary) {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
  flex: 0 0 auto;
  padding: 8px;
}

.action-btn:not(.primary):hover {
  background: #e5e7eb;
}

.load-more {
  text-align: center;
  margin-top: 40px;
}

.load-more-btn {
  padding: 12px 24px;
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  color: #374151;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.load-more-btn:hover {
  border-color: #667eea;
  color: #667eea;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.loading-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.skeleton {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
}

.skeleton-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #e5e7eb;
  margin-bottom: 16px;
  animation: pulse 2s infinite;
}

.skeleton-content {
  flex: 1;
}

.skeleton-title {
  height: 20px;
  background: #e5e7eb;
  border-radius: 4px;
  margin-bottom: 8px;
  animation: pulse 2s infinite;
}

.skeleton-desc {
  height: 16px;
  background: #e5e7eb;
  border-radius: 4px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@media (max-width: 768px) {
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .role-actions {
    flex-direction: column;
  }
  
  .role-stats {
    flex-direction: column;
    gap: 8px;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .filter-tabs {
    flex-wrap: wrap;
  }
}
</style>
